package com.alice.item.service;

import com.alice.item.mapper.ItemMapper;
import com.alice.item.pojo.Item;
import com.alice.item.pojo.ItemForm;
import com.alice.item.pojo.ItemVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

/**
 * Created by caoxuel on 2020/9/22 13:20
 */
@Service
public class ItemService {

    @Autowired
    private ItemMapper itemMapper;

    /**
     * 根据id查询商品
     * @param id
     * @return
     */
    public Item queryById(Integer id){
        return itemMapper.selectByPrimaryKey(id);
    }

    /**
     * 不查询已经删除的商品
     * @return
     */
    public List<Item> queryItemList(){
        Example example = new Example(Item.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andNotEqualTo("status", 3);

        List<Item> list = itemMapper.selectByExample(example);
        return list;
    }

    /**
     * 添加商品
     * @param item
     */
    public void addItem(Item item){
        itemMapper.insert(item);
    }

    /**
     * 逻辑删除商品
     * @param id
     */
    public void deleteById(Integer id){
        Item item = queryById(id);
        //商品状态，1：正常 ，2：下架，3：删除
        item.setStatus(3);
        itemMapper.updateByPrimaryKey(item);
    }

    /**
     * 修改商品信息
     * @param itemForm
     */
    public void updateItem(ItemForm itemForm){
        Item item = queryById(itemForm.getId());
        item.setUpdated(new Date());
        item.setTitle(itemForm.getTitle());
        item.setStatus(itemForm.getStatus());
        item.setCid(itemForm.getCid());
        item.setNum(itemForm.getNum());
        item.setPrice(itemForm.getPrice());
        item.setSellPoint(itemForm.getSellPoint());
        itemMapper.updateByPrimaryKey(item);
    }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @param item
     * @return
     */
    public List<Item> queryPagedItem(Integer page, Integer pageSize, ItemVo item) {

        /**
         * page: 第几页
         * pageSize: 每页显示条数
         */
        PageHelper.startPage(page, pageSize);
        List<Item> list;
        if(item==null){
            return queryItemList();
        }
        Example example = new Example(Item.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andNotEqualTo("status", 3);
        if(!StringUtils.isEmpty(item.getTitle())){
            criteria.andLike("title", item.getTitle());
        }
        if(item.getCid()!=null){
            criteria.andEqualTo("cid", item.getCid());
        }
        list = itemMapper.selectByExample(example);
        return list;
    }
}
